package com.calvin.demos.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.excel.EasyExcel;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;

@Controller
@RequestMapping("/easyexcel")
public class EasyExcelController extends BaseController {
	
	List<List<Object>> data = null;
	
	@GetMapping("export")
	public void export() throws IOException {
		try {
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");

			// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
			String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			// 这里需要设置不关闭流
			EasyExcel.write(response.getOutputStream(), User.class).autoCloseStream(Boolean.FALSE).sheet("模板")
					.doWrite(getData());
		} catch (Exception e) {
			 // 重置response
            response.reset();
            //response.setContentType("application/json");
            //response.setCharacterEncoding("utf-8");
            response.setHeader("content-type", "text/html;charset=utf-8");
            Map<String, String> map = MapUtil.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONUtil.toJsonStr(map));
		}
	}

	
	
	private List<List<Object>> getData() {
		data = new ArrayList<>();
		for (int i = 0; i < 100000; i++) {
			data.add(ListUtil.of(RandomUtil.randomString(6), RandomUtil.randomInt(0, 99), i));
		}
		return data;
	}
}
